package com.imooc.set_;

import java.util.HashSet;

/**
 * @Date:2022/4/6/22:58
 * @Description:练习：
 * 定义一个Employee类，该类包含：private成员属性name，age 要求：
 *      1 创建3个Employee 对象放入 HashSet中
 *      2 当 name和 age的值相同时，认为是相同员工，不能添加到HashSet集合中
 */
public class HashSetExercise {
    public static void main(String[] args) {
        HashSet<Object> hashSet = new HashSet<>();
        hashSet.add(new Employee("tom",18));
        hashSet.add(new Employee("tom",18));
        hashSet.add(new Employee("lili",20));

        for (Object o :hashSet) {
            System.out.println("o = " + o);
        }

    }
}

class Employee{
    private String name;
    private int age;

    public Employee(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Employee employee = (Employee) o;

        if (age != employee.age) return false;
        return name != null ? name.equals(employee.name) : employee.name == null;
    }

    @Override
    public int hashCode() {
        int result = name != null ? name.hashCode() : 0;
        result = 31 * result + age;
        return result;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}